// src/store/authStore.js
import { create } from 'zustand';
import axios from '../api/axios';
import { endpoints } from '../api/endpoints';
import { getToken, setToken, removeToken,setUserData, getUserId } from '../utils/storage';


export const useAuthStore = create((set, get) => ({
  isAuthenticated: false,
  loading: false,
  error: null,
  
  // Check if user is authenticated
  checkAuth: () => {
    const token = getToken();
    set({ isAuthenticated: !!token });
    return !!token;
  },
  
  // Login user
  login: async (email, password) => {
    set({ loading: true, error: null });
    try {
      const response = await axios.post(endpoints.login, {
        identity: email,
        password: password
      });
      const { token, record } = response.data;
      setToken(token);
      setUserData(record);
      set({ isAuthenticated: true, loading: false });
      return response;
    } catch (error) {
      set({ 
        error: error.response?.data?.message || "Login failed", 
        loading: false 
      });
      throw error;
    }
  },
  
  // Register user
  register: async (userData) => {
    set({ loading: true, error: null });
    try {
      const response = await axios.post(endpoints.register, userData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      set({ loading: false });
      return response;
    } catch (error) {
      set({ 
        error: error.response?.data?.message || "Registration failed", 
        loading: false 
      });
      throw error;
    }
  },
  
  // Logout user
  logout: () => {
    removeToken();
    set({ isAuthenticated: false });
  },

  // Clear errors
  clearErrors: () => set({ error: null }),

  // Get user info
  getUserInfo: async () => {
    const userId = getUserId();
    if (!userId) return null;

    try {
      const response = await axios.get(`${endpoints.getUserInfo}${userId}`);
      return response.data;
    } catch (error) {
      removeToken();
      console.error("Failed to fetch user info:", error);
      throw error;
    }
  },

  // Update user profile
  updateProfile: async (userData) => {
    set({ loading: true, error: null });
    try {
      const userId = getUserId();
      if (!userId) throw new Error('User ID not found');
      
      const response = await axios.put(`/api/custom/tis/update-profile/users/${userId}`, userData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      set({ loading: false });
      return response;
    } catch (error) {
      set({ 
        error: error.response?.data?.message || "Profile update failed", 
        loading: false 
      });
      throw error;
    }
  },
}));
